package info.xinfu.carban.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import info.xinfu.carban.R;
import info.xinfu.carban.adapter.MobileListAdapter;
import info.xinfu.carban.base.BaseFragment;
import info.xinfu.carban.entity.MobileObserver;
import info.xinfu.carban.utils.Constants;
import info.xinfu.carban.utils.DividerItemDecoration;
import info.xinfu.carban.utils.SPUtils;
import com.xinfu.xrecyclerview.XRecyclerView;
import com.google.gson.Gson;
import com.hui.util.log.LogUtils;
import com.vondear.rxtools.RxNetUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.MediaType;

public class SellerMobileListFragment extends BaseFragment {
    @BindView(R.id.recyclerView_mobile)
    XRecyclerView mRecyclerView;
    //存放请假类型的map
    protected float[] mValues = new float[]{25.14f, 74.86f};
    protected float[] mValues2 = new float[]{35.20f, 64.8f};
    @BindView(R.id.btn_bottom)
    Button btnBottom;
    Unbinder unbinder;
    @BindView(R.id.fee_mobile)
    EditText feeMobile;
    @BindView(R.id.fee_good)
    TextView feeGood;
    private int mYear;
    private boolean isFirstEntry = false;

    private String mDate = "";
    //当前页码
    private int pageNo = 1;
    private boolean isLastPage = false;

    List<MobileObserver> mData = new ArrayList<MobileObserver>();
    private MobileListAdapter mAdapterRank;

    public static SellerMobileListFragment getInstance(String type) {
        SellerMobileListFragment fragment1 = new SellerMobileListFragment();
        Bundle bdl = new Bundle();
        bdl.putString("type", type);
        fragment1.setArguments(bdl);
        return fragment1;
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
        initRecyclerView();
    }

    @Override
    protected void initData() {
        getData();

    }

    @Override
    protected int getRootViewId() {
        return R.layout.fragment_mobile_list;
    }

    private void initRecyclerView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        //一个小问题，触摸到RecyclerView的时候滑动还有些粘连的感觉
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(context));
        mRecyclerView.setHasFixedSize(true);
        mData = new ArrayList<MobileObserver>();
        mAdapterRank = new MobileListAdapter(R.layout.item_mobile_content, mData);
        mRecyclerView.setAdapter(mAdapterRank);
        mRecyclerView.setLoadingMoreEnabled(false);
        mAdapterRank.setEnableLoadMore(false);
        mAdapterRank.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                deleteMobileConfirm(mData.get(position -1 ).getId());
            }
        });
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getData();
            }

            @Override
            public void onLoadMore() {

            }
        });
    }

    private void getData() {
        final String uname = SPUtils.getString(Constants.username, "");

        if (RxNetUtils.isAvailable(context)) {
            String akey = SPUtils.getString(Constants.accessKey, "");
            OkHttpUtils.post().url(Constants.getmobilelist)
                    .addParams(Constants.username, uname)

                    .build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    LogUtils.e(e.getMessage());

                }

                @Override
                public void onResponse(String response, int id) {
                    LogUtils.w(response);
                    mData.clear();
                    if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                        List<MobileObserver> MobileObservers = JSON.parseArray(response, MobileObserver.class);
                        mData.addAll(MobileObservers);
                        mAdapterRank.notifyDataSetChanged();
                        mRecyclerView.refreshComplete();
                    } else {
                        showToast("数据错误");
                    }

                }
            });
        } else {

        }

    }

    @OnClick({R.id.btn_bottom})
    void onClick(View view) {
        switch (view.getId()) {

            case R.id.btn_bottom:
                if (!TextUtils.isEmpty(feeMobile.getText().toString()))
                    connectNetToSubmit();
                else
                    showToast("请填写手机号");
                break;
            default:

                break;
        }
    }

    /**
     * 联网提交
     */
    private void connectNetToSubmit() {
        /**
         * 字段{userId:,postId:}
         * post json 方式
         */
        MobileObserver write_post = new MobileObserver();

        String uname = SPUtils.getString(Constants.username, "");
        write_post.setMobile(feeMobile.getText().toString());
        write_post.setUserId(uname);

        OkHttpUtils.postString().url(Constants.addUserMobile)
                .content(new Gson().toJson(write_post))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //结束时别忘了hideDialog（）;
                        hidePDialog();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //结束时别忘了hideDialog;
                        hidePDialog();
                        LogUtils.e(response);
                        if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                            JSONObject jsonObject = JSON.parseObject(response);
                            String errorFlag = jsonObject.getString("errorFlag");
                            if (!errorFlag.equals("-1")) {
                                //success
                                showToast("添加成功");
//                                EventBus.getDefault().post(new Event_Send_mobile_Message(true));
                                getData();
                            } else {
                                //error
                                showToast("该手机号已添加过~");
                            }
                        } else {
                            //error
                            showToast("添加失败~");
                        }
                    }
                });

    }


    protected void deleteMobileConfirm(final int id) {
        new AlertDialog.Builder(context).setTitle("提示：")
                .setMessage("确定删除该手机号码吗？")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteMobile(id);
                dialog.dismiss();

            }
        }).show();


    }
    /**
     * 删除手机号码
     */
    private void deleteMobile(int id) {
        /**
         * 字段{userId:,postId:}
         * post json 方式
         */
        MobileObserver write_post = new MobileObserver();

        String uname = SPUtils.getString(Constants.username, "");
        write_post.setMobile(feeMobile.getText().toString());
        write_post.setUserId(uname);

        OkHttpUtils.post().url(Constants.deleteUserMobile)
                .addParams("id", String.valueOf(id))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        //结束时别忘了hideDialog（）;
                        hidePDialog();
                        showToast(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        //结束时别忘了hideDialog;
                        hidePDialog();
                        LogUtils.e(response);
                        if (!TextUtils.isEmpty(response) && isGoodJson(response)) {
                            showToast("删除成功");
                            getData();
                        } else {
                            //error
                            showToast("删除失败~");
                        }
                    }
                });

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
